package app.view;

import java.awt.Component;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;

import javax.swing.JComponent;
import javax.swing.JTable;
import javax.swing.JTextField;

public class TextCellEditor extends javax.swing.AbstractCellEditor implements
		javax.swing.table.TableCellEditor {

	private static final long serialVersionUID = 1L;
	
	private JComponent component = new JTextField();
	
	private ArrayList<EditingFinishedListener> listeners = new ArrayList<EditingFinishedListener>();

	public void addListener(EditingFinishedListener efl) {
		listeners.add(efl);
	}
	
	public TextCellEditor() {
		super();
		
		((JTextField) component).addFocusListener(new FocusListener() {

			@Override
			public void focusLost(FocusEvent arg0) {
			}

			@Override
			public void focusGained(FocusEvent arg0) {
				((JTextField) component).selectAll();
			}
		});
		
		((JTextField) component).addKeyListener(new KeyListener() {
			
			@Override
			public void keyTyped(KeyEvent arg0) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void keyReleased(KeyEvent arg0) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void keyPressed(KeyEvent arg0) {
				if (arg0.getKeyCode() == KeyEvent.VK_TAB) {
					arg0.consume();
					
					for (EditingFinishedListener efl : listeners)
						efl.trigger();
					
				}
			}
		});
	}

	public Component getTableCellEditorComponent(JTable table, Object value,
			boolean isSelected, int rowIndex, int vColIndex) {
		// 'value' is value contained in the cell located at (rowIndex,
		// vColIndex)

		if (isSelected) {
			// cell (and perhaps other cells) are selected
		}

		// Configure the component with the specified value
		((JTextField) component).setText((String) value);

		// Return the configured component
		return component;
	}

	// This method is called when editing is completed.
	// It must return the new value to be stored in the cell.
	public Object getCellEditorValue() {
		return ((JTextField) component).getText();
	}

}
